<template>
  <div class="teacher-course-container">
    <el-page-header @back="goBack" class="page-header">
      <template #content>
        <div class="header-content">
          <span class="header-title">{{ courseInfo.name }}</span>
          <el-tag :type="courseStatusTagType" effect="dark">
            {{ courseStatusText }}
          </el-tag>
        </div>
      </template>
    </el-page-header>

    <el-card class="main-card">
      <!-- 课程基本信息 -->
      <div class="course-basic-info">
        <div class="course-cover">
          <img :src="courseInfo.pic || defaultCourseImage" :alt="courseInfo.name">
          <div v-if="courseInfo.price > 0" class="price-tag">
            ¥{{ courseInfo.price }}
          </div>
        </div>
        <div class="course-meta">
          <div class="meta-grid">
            <div class="meta-item">
              <span class="label">课程ID:</span>
              <span>{{ courseInfo.id }}</span>
            </div>
            
            <div class="meta-item">
              <span class="label">课程价格:</span>
              <span>{{ courseInfo.price > 0 ? `¥${courseInfo.price}` : '免费' }}</span>
            </div>
            <div class="meta-item">
              <span class="label">收藏人数:</span>
              <span>{{ courseInfo.collectionCount }}</span>
            </div>
            <div class="meta-item">
              <span class="label">浏览次数:</span>
              <span>{{ courseInfo.clicks }}</span>
            </div>
            <div class="meta-item">
              <span class="label">点赞数:</span>
              <span>{{ courseInfo.likeCount }}</span>
            </div>
            <div class="meta-item">
              <span class="label">分享数:</span>
              <span>{{ courseInfo.shareCount }}</span>
            </div>
            <div class="meta-item">
              <span class="label">购买人数:</span>
              <span>{{ courseInfo.purchaseCount }}</span>
            </div>
            <div class="meta-item" v-if="isCourseTeacher">
              <span class="label">课程状态:</span>
              <el-select 
                v-model="courseInfo.status" 
                @change="updateCourseStatus"
              >
                <el-option label="未发布" :value="0" />
                <el-option label="已发布" :value="1" />
                <el-option label="已下架" :value="2" />
              </el-select>
            </div>
            <div class="meta-item" v-else>
              <span class="label">课程状态:</span>
              <span>{{ courseStatusText }}</span>
            </div>
          </div>
        </div>
      </div>

      <el-tabs v-model="activeTab" class="course-tabs">
        <!-- 课程介绍 -->
        <el-tab-pane label="课程介绍" name="intro">
          <div class="course-intro">
            <el-input
              v-if="isCourseTeacher"
              v-model="courseInfo.introduction"
              type="textarea"
              :rows="5"
              placeholder="请输入课程介绍"
              @blur="updateCourseIntro"
            />
            <div v-else v-html="courseInfo.introduction || '暂无课程介绍'"></div>
          </div>
        </el-tab-pane>
        
        <!-- 课程评价 -->
        <el-tab-pane label="课程评价" name="reviews">
          <div class="course-reviews">
            <div v-if="courseInfo.appraises?.length > 0">
              <div v-for="review in courseInfo.appraises" :key="review.id" class="review-item">
                <div class="review-header">
                  <span class="review-author">学生ID: {{ review.studentId }}</span>
                  <el-rate 
                    v-model="review.score" 
                    disabled 
                    show-score 
                    :max="5"
                    score-template="{value} 分"
                  />
                </div>
                <div class="review-content">
                  {{ review.content }}
                </div>
                <div class="review-time">
                  {{ formatDate(review.createTime) }}
                </div>
              </div>
            </div>
            <el-empty v-else description="暂无评价数据" />
          </div>
        </el-tab-pane>
        
        <!-- 学生管理 -->
        <el-tab-pane label="学生管理" name="students" v-if="isCourseTeacher">
          <div class="student-management">
            <div class="student-search">
              <el-input
                v-model="studentSearchQuery"
                placeholder="搜索学生姓名或学号"
                clearable
                style="width: 300px"
                @keyup.enter="searchStudents"
              />
              <el-button type="primary" @click="searchStudents" icon="Search">
                搜索
              </el-button>
            </div>
            
            <el-table :data="filteredStudents" border style="width: 100%">
              <el-table-column prop="name" label="学生姓名" width="120" />
              <el-table-column prop="studentId" label="学号" width="120" />
              <el-table-column prop="joinTime" label="加入时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.joinTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="progress" label="学习进度">
                <template #default="{ row }">
                  <el-progress :percentage="row.progress || 0" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="{ row }">
                  <el-button type="text" @click="viewStudentDetail(row)">详情</el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <el-pagination
              v-if="filteredStudents.length > 0"
              :current-page="studentCurrentPage"
              :page-size="studentPageSize"
              :total="filteredStudents.length"
              layout="prev, pager, next, jumper"
              @current-change="handleStudentPageChange"
              class="student-pagination"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 章节编辑对话框 -->
    <el-dialog 
      v-model="showChapterDialog" 
      :title="currentChapter.id ? '编辑章节' : '添加章节'"
      width="50%"
    >
      <el-form :model="chapterForm" label-width="80px">
        <el-form-item label="章节标题" required>
          <el-input v-model="chapterForm.cha_title" placeholder="请输入章节标题" />
        </el-form-item>
        <el-form-item label="排序号">
          <el-input-number v-model="chapterForm.sort_order" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showChapterDialog = false">取消</el-button>
        <el-button type="primary" @click="submitChapter">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 视频编辑对话框 -->
    <el-dialog 
      v-model="showVideoDialog" 
      :title="currentVideo.id ? '编辑视频' : '添加视频'"
      width="60%"
    >
      <el-form :model="videoForm" label-width="100px">
        <el-form-item label="所属章节" required>
          <el-select v-model="videoForm.chapterId" placeholder="请选择章节">
            <el-option
              v-for="chapter in chapters"
              :key="chapter.id"
              :label="`第${chapter.sort_order}章 ${chapter.cha_title}`"
              :value="chapter.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="视频标题" required>
          <el-input v-model="videoForm.title" placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="排序号">
          <el-input-number v-model="videoForm.sort_order" :min="1" />
        </el-form-item>
        <el-form-item label="视频时长(秒)">
          <el-input-number v-model="videoForm.duration" :min="0" />
        </el-form-item>
        <el-form-item label="视频URL" required>
          <el-input v-model="videoForm.url" placeholder="请输入视频URL" />
        </el-form-item>
        <el-form-item label="封面图">
          <el-input v-model="videoForm.cover" placeholder="请输入封面图URL" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showVideoDialog = false">取消</el-button>
        <el-button type="primary" @click="submitVideo">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { 
  ElMessage, 
  ElMessageBox,
  ElLoading
} from 'element-plus'
import { VideoPlay, Plus, Search } from '@element-plus/icons-vue'
import { teacherApi } from '@/api/teacher'
import { courseApi } from '@/api/course'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 课程数据
const loading = ref(true)
const courseInfo = ref({
  id: '',
  name: '',
  introduction: '',
  pic: '',
  price: 0,
  collectionCount: 0,
  clicks: 0,
  status: 0,
  createTime: '',
  teacherId: '',
  likeCount: 0,
  shareCount: 0,
  purchaseCount: 0,
  appraises: []
})
const chapters = ref([])
const defaultCourseImage = ref(require('@/assets/fault.png'))

// 权限控制
const isCourseTeacher = ref(false)

// 标签页控制
const activeTab = ref('intro')
const activeChapter = ref('')

// 学生管理
const students = ref([])
const studentSearchQuery = ref('')
const studentCurrentPage = ref(1)
const studentPageSize = ref(10)

// 对话框控制
const showVideoDialog = ref(false)
const currentVideo = ref({})
const showChapterDialog = ref(false)
const currentChapter = ref({})

// 表单数据
const chapterForm = ref({
  id: '',
  cou_id: '',
  cha_title: '',
  sort_order: 1
})

const videoForm = ref({
  id: '',
  chapterId: '',
  title: '',
  sort_order: 1,
  duration: 0,
  url: '',
  cover: ''
})

// 计算属性
const courseStatusText = computed(() => {
  const statusMap = {
    0: '未发布',
    1: '已发布',
    2: '已下架'
  }
  return statusMap[courseInfo.value.status] || '未知状态'
})

const courseStatusTagType = computed(() => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'danger'
  }
  return typeMap[courseInfo.value.status] || 'info'
})

const filteredStudents = computed(() => {
  let result = students.value
  if (studentSearchQuery.value) {
    const query = studentSearchQuery.value.toLowerCase()
    result = result.filter(s => 
      (s.name && s.name.toLowerCase().includes(query)) ||
      (s.studentId && s.studentId.toLowerCase().includes(query))
    )
  }
  const start = (studentCurrentPage.value - 1) * studentPageSize.value
  const end = start + studentPageSize.value
  return result.slice(start, end)
})

// 排序后的章节
const sortedChapters = computed(() => {
  return [...chapters.value].sort((a, b) => a.sort_order - b.sort_order)
})

// 方法
const goBack = () => {
  router.go(-1)
}

const formatDate = (dateString) => {
  return dateString ? dayjs(dateString).format('YYYY-MM-DD HH:mm') : '未知时间'
}

const formatDuration = (seconds) => {
  if (!seconds) return '00:00'
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 排序视频
const sortedVideos = (videos) => {
  return [...(videos || [])].sort((a, b) => a.sort_order - b.sort_order)
}

const fetchCourseDetail = async () => {
  try {
    loading.value = true
    const courseId = route.params.id
    const teacherId = authStore.userId
    
    // 获取课程详情
    const [courseRes, permissionRes] = await Promise.all([
      courseApi.getCourseDetail(courseId),
      teacherApi.checkTeachingPermission(teacherId, courseId)
    ])
    
    // 设置课程信息
    const courseData = courseRes.data || courseRes
    courseInfo.value = {
      ...courseInfo.value,
      ...courseData,
      appraises: courseData.appraises || []
    }
    
    // 检查教师权限（即使权限检查返回false，如果是课程创建者仍然可以编辑）
    isCourseTeacher.value = permissionRes.data === true || 
                          courseData.teacherId === teacherId
    
    // 获取章节数据
    const chaptersRes = await courseApi.getChapterTree(courseId)
    const chaptersData = chaptersRes.data || chaptersRes || []
    
    // 格式化章节数据
    chapters.value = chaptersData.map(chapter => ({
      ...chapter,
      videos: chapter.videos || []
    }))
    
    // 如果是教师，获取学生数据
    if (isCourseTeacher.value) {
      const studentsRes = await teacherApi.getCourseStudents(courseId)
      students.value = studentsRes.data || studentsRes || []
    }
    
    ElMessage.success('课程数据加载成功')
  } catch (error) {
    console.error('获取课程详情失败:', error)
    ElMessage.error('获取课程详情失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const updateCourseStatus = async () => {
  if (!isCourseTeacher.value) return
  
  try {
    await courseApi.publishCourse(courseInfo.value.id)
    ElMessage.success('课程状态更新成功')
  } catch (error) {
    console.error('更新课程状态失败:', error)
    ElMessage.error('更新课程状态失败: ' + error.message)
    // 恢复原状态
    await fetchCourseDetail()
  }
}

const updateCourseIntro = async () => {
  if (!isCourseTeacher.value) return
  
  try {
    await courseApi.updateCourseInfo(courseInfo.value.id, {
      name: courseInfo.value.name,
      introduction: courseInfo.value.introduction
    })
    ElMessage.success('课程介绍更新成功')
  } catch (error) {
    console.error('更新课程介绍失败:', error)
    ElMessage.error('更新课程介绍失败: ' + error.message)
    // 恢复原介绍
    await fetchCourseDetail()
  }
}

const editChapter = (chapter) => {
  if (!isCourseTeacher.value) return
  
  currentChapter.value = chapter
  chapterForm.value = { 
    ...chapter,
    cou_id: courseInfo.value.id
  }
  showChapterDialog.value = true
}

const addChapter = () => {
  if (!isCourseTeacher.value) return
  
  currentChapter.value = {}
  chapterForm.value = {
    id: '',
    cou_id: courseInfo.value.id,
    cha_title: '',
    sort_order: chapters.value.length + 1
  }
  showChapterDialog.value = true
}

const editVideo = (video) => {
  if (!isCourseTeacher.value) return
  
  currentVideo.value = video
  videoForm.value = { 
    ...video,
    chapterId: video.chapter_id || video.chapterId
  }
  showVideoDialog.value = true
}

const addVideo = () => {
  if (!isCourseTeacher.value) return
  
  currentVideo.value = {}
  videoForm.value = {
    id: '',
    chapterId: sortedChapters.value[0]?.id || '',
    title: '',
    sort_order: 1,
    duration: 0,
    url: '',
    cover: ''
  }
  showVideoDialog.value = true
}

const deleteVideo = async (video) => {
  if (!isCourseTeacher.value) return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除视频 "${video.title}" 吗？`, 
      '警告', 
      { type: 'warning' }
    )
    await courseApi.deleteVideo(video.id)
    ElMessage.success('视频删除成功')
    await fetchCourseDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除视频失败:', error)
      ElMessage.error('删除视频失败: ' + error.message)
    }
  }
}

const submitChapter = async () => {
  try {
    if (chapterForm.value.id) {
      await courseApi.updateChapter(chapterForm.value.id, chapterForm.value)
    } else {
      await courseApi.createChapter(chapterForm.value)
    }
    ElMessage.success('章节保存成功')
    showChapterDialog.value = false
    await fetchCourseDetail()
  } catch (error) {
    console.error('保存章节失败:', error)
    ElMessage.error('保存章节失败: ' + error.message)
  }
}

const submitVideo = async () => {
  try {
    if (videoForm.value.id) {
      await courseApi.updateVideo(videoForm.value)
    } else {
      await courseApi.addVideo(videoForm.value)
    }
    ElMessage.success('视频保存成功')
    showVideoDialog.value = false
    await fetchCourseDetail()
  } catch (error) {
    console.error('保存视频失败:', error)
    ElMessage.error('保存视频失败: ' + error.message)
  }
}

const searchStudents = () => {
  studentCurrentPage.value = 1
}

const handleStudentPageChange = (page) => {
  studentCurrentPage.value = page
}

const viewStudentDetail = (student) => {
  router.push({
    name: 'StudentCourseDetail',
    params: { 
      studentId: student.id,
      courseId: courseInfo.value.id
    }
  })
}

onMounted(() => {
  fetchCourseDetail()
})
</script>

<style scoped>
.teacher-course-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.main-card {
  margin-bottom: 20px;
}

.course-basic-info {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.course-cover {
  width: 300px;
  height: 180px;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
  position: relative;
}

.course-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.price-tag {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 14px;
  z-index: 1;
}

.course-meta {
  flex: 1;
}

.meta-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
}

.meta-item .label {
  color: #606266;
  margin-right: 10px;
  width: 100px;
  text-align: right;
}

.course-tabs {
  margin-top: 20px;
}

.course-intro {
  line-height: 1.6;
  padding: 10px;
}

.chapter-list {
  margin-top: 20px;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.chapter-title {
  font-weight: 500;
}

.video-list {
  padding: 0 10px;
}

.video-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
  transition: background-color 0.3s;
}

.video-item:hover {
  background-color: #f5f7fa;
}

.video-info {
  display: flex;
  align-items: center;
  gap: 15px;
  flex: 1;
}

.video-index {
  color: #999;
  width: 60px;
}

.video-title {
  flex: 1;
}

.video-duration {
  color: #666;
  width: 60px;
  text-align: right;
}

.video-actions {
  margin-left: 20px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.course-reviews {
  padding: 15px;
}

.review-item {
  padding: 15px;
  margin-bottom: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.review-author {
  font-weight: bold;
}

.review-content {
  color: #606266;
  margin-bottom: 10px;
}

.review-time {
  color: #909399;
  font-size: 12px;
  text-align: right;
}

.student-management {
  margin-top: 20px;
}

.student-search {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.student-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .course-basic-info {
    flex-direction: column;
  }
  
  .course-cover {
    width: 100%;
    height: auto;
    aspect-ratio: 16/9;
  }
  
  .meta-grid {
    grid-template-columns: 1fr;
  }
  
  .video-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .video-actions {
    margin-left: 0;
    width: 100%;
    justify-content: flex-end;
  }
  
  .student-search {
    flex-direction: column;
  }
  
  .student-search .el-input {
    width: 100% !important;
  }
}
</style>